package main

import (
	"fmt"
	"server/cs"

	"github.com/eapache/channels"
)

type player struct {
	playerID uint32
	ch       *channels.RingChannel // cache all UpdateMessages
}

func newPlayer(playerID uint32) *player {
	return &player{
		playerID: playerID,
		ch:       channels.NewRingChannel(100), // 玩家数不能大于 100
	}
}

func (p *player) GetPlayerID() uint32 {
	return p.playerID
}

// RunReceiveUpdate 接收其他玩家的更新，发送回stream
func (p *player) RunReceiveUpdate(stream cs.Game_ReceiveUpdateServer) error {
	fmt.Printf("RunReceiveUpdate(PlayerID=%d) start...\n", p.playerID)
	defer fmt.Printf("RunReceiveUpdate(PlayerID=%d) end.\n", p.playerID)

	for {
		itf := <-p.ch.Out()
		msg := itf.(*cs.UpdateMessage)
		if err := stream.Send(msg); err != nil {
			fmt.Printf("stream send error(PlayerID=%d): %s\n", p.playerID, err)
			return err
		}
	}
	return nil
}

// PushUpdateMessage 压入更新消息，待发送
func (p *player) PushUpdateMessage(msg *cs.UpdateMessage) {
	p.ch.In() <- msg
}
